package org.example.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.example.MemberGroupRequestPacket;
import org.example.MemberGroupResponsePacket;
import org.example.QuitGroupRequestPacket;
import org.example.QuitGroupResponsePacket;
import org.example.im.SessionUtil;

import java.util.ArrayList;
import java.util.List;

public class MemberGroupRequestHandler extends SimpleChannelInboundHandler<MemberGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MemberGroupRequestPacket memberGroupRequestPacket) {
        System.out.println("服务端处理查看群成员列表的请求逻辑...收到的参数:" + memberGroupRequestPacket);
        // 1、获取群聊id
        ChannelGroup channelGroup = SessionUtil.getGroup(memberGroupRequestPacket.getGroupId());

        List<String> userIds = new ArrayList<>();
        for (Channel channel : channelGroup) {
            userIds.add(SessionUtil.getUserId(channel));
        }

        // 2、发送响应报文
        MemberGroupResponsePacket memberGroupResponsePacket = MemberGroupResponsePacket.builder()
                .success(true)
                .userIds(userIds)
                .groupId(memberGroupRequestPacket.getGroupId())
                .build();

        ctx.channel().writeAndFlush(memberGroupResponsePacket);
    }
}
